package cbfg.rvadapter.selection.store

import java.util.TreeSet

/**
 * 索引映射，用于记录索引与数据的对应关系
 */
class IndexMap<K>(descending: Boolean) : MutableMap<K, Int> {
    private val map = HashMap<K, Int>()
    private val set = TreeSet<K> { o1, o2 ->
        if (descending) map[o2]!! - map[o1]!!
        else map[o1]!! - map[o2]!!
    }

    override val entries: MutableSet<MutableMap.MutableEntry<K, Int>>
        get() = map.entries

    override val keys: MutableSet<K>
        get() = set

    override val size: Int
        get() = map.size

    override val values: MutableCollection<Int>
        get() = map.values

    override fun isEmpty(): Boolean = set.isEmpty()

    override fun get(key: K): Int? = map[key]

    override fun containsValue(value: Int): Boolean = map.containsValue(value)

    override fun containsKey(key: K): Boolean = set.contains(key)

    override fun clear() {
        map.clear()
        set.clear()
    }

    override fun remove(key: K): Int? {
        return map.remove(key)?.also {
            set.remove(key)
        }
    }

    override fun putAll(from: Map<out K, Int>) {
        map.putAll(from)
        set.addAll(from.keys)
    }

    override fun put(key: K, value: Int): Int? {
        map[key] = value
        set.add(key)
        return value
    }
}